package com.jsgt.greekfire.ui.market

import android.content.Intent
import android.widget.CompoundButton
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseFragment
import com.jsgt.greekfire.LOGIN_STATUS
import com.jsgt.greekfire.R
import com.jsgt.greekfire.dao.model.MarketBean
import com.jsgt.greekfire.common.containsIgnoreCase
import com.jsgt.greekfire.dao.viewmodel.MarketBeanViewModel
import com.jsgt.greekfire.dao.viewmodel.MarketBeanViewModelFactory
import com.jsgt.greekfire.dao.viewmodel.NetLoadResultObserver
import com.jsgt.greekfire.event.MarketEvent
import com.jsgt.greekfire.ui.home.adapter.MarketAdapter
import com.jsgt.greekfire.factory.CoinViewModelFactory
import com.jsgt.greekfire.ui.trading.SearchCoinActivity
import com.jsgt.greekfire.viewmodel.CoinViewModel
import com.scwang.smartrefresh.header.MaterialHeader
import kotlinx.android.synthetic.main.fragment_market.*
import kotlinx.android.synthetic.main.view_market_top.*
import kotlinx.android.synthetic.main.view_nav_single_ch.*
import kotlinx.android.synthetic.main.view_nav_single_ch.radioGroup
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 行情
 */
class MarketFragment : BaseFragment() {
    private val coinViewModel: CoinViewModel by lazy {
        ViewModelProvider(
            this,
            CoinViewModelFactory()
        ).get(CoinViewModel::class.java)
    }

    private val marketBeanViewModel: MarketBeanViewModel by lazy {
        ViewModelProvider(
            this,
            MarketBeanViewModelFactory(
                requireContext(),
                resources.getStringArray(R.array.market_list)
            )
        ).get(MarketBeanViewModel::class.java)
    }


    val list: MutableList<MarketBean> = ArrayList()
    var marketAdapter = MarketAdapter()
    private var sortType: String = ""
    private var sortCheck: Boolean = false
    override fun getLayoutId(): Int = R.layout.fragment_market
    override fun main() {
        market_rv.adapter = marketAdapter
        coin_type_cb.setOnCheckedChangeListener(onCheckedChangeListener)
        new_price_cb.setOnCheckedChangeListener(onCheckedChangeListener)
        income_24h_cb.setOnCheckedChangeListener(onCheckedChangeListener)
        marketAdapter.itemClickListner = {
            MarketDetailActivity.start(requireContext(), it)
        }
        refresh_layout.setRefreshHeader(MaterialHeader(context).setColorSchemeResources(R.color.black))
        refresh_layout.setEnableLoadMore(false)
        refresh_layout.setOnRefreshListener {
            loadAll()
        }
        search_iv.setOnClickListener {
            startActivity(Intent(activity, SearchCoinActivity::class.java))
        }
        nav_rb_2.isChecked = true
        radioGroup.setOnCheckedChangeListener { _, checkedId ->
            run {
                if (checkedId == nav_rb_1.id) {
                    if (LOGIN_STATUS) {
                        coinViewModel.getMyMarketList(
                            "currentPrice",
                            true
                        )
                    } else {
                        marketAdapter.clearData()
                    }

                } else if (checkedId == nav_rb_2.id) {
                    coinViewModel.getMarketList("name", false)
                }
            }
        }
        coinViewModel.myMarketListLiveData.observe(this, Observer {
            refresh_layout.finishRefresh()
            list.clear()
            list.addAll(it)
            marketAdapter.refreshData(list)

        })

        coinViewModel.errorLiveData.observe(this, Observer {
            refresh_layout.finishRefresh()
        })

        marketBeanViewModel.marketListLiveData?.observe(this, Observer {
            list.clear()
            list.addAll(it)
            marketAdapter.refreshData(list)
        })

        marketBeanViewModel.netLoadLiveData.observe(this, object : NetLoadResultObserver() {
            override fun onSuccess() {
                refresh_layout.finishRefresh()
            }

            override fun onError(msg: String?) {
                refresh_layout.finishRefresh()
            }
        })
        refresh_layout.autoRefresh()
//        loadAll()
    }

    private val onCheckedChangeListener =
        CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            sortCheck = isChecked
            when (buttonView!!.id) {
                R.id.coin_type_cb -> {
                    if (sortCheck) {
                        list.sortBy { it.symbol }
                        marketAdapter.refreshData(list)
                    } else {
                        list.sortByDescending { it.symbol }
                        marketAdapter.refreshData(list)
                    }
                }
                R.id.new_price_cb -> {

                    if (sortCheck) {
                        list.sortBy { it.volume.toString() }
                        marketAdapter.refreshData(list)
                    } else {
                        list.sortByDescending { it.volume.toString() }
                        marketAdapter.refreshData(list)
                    }
                }
                R.id.income_24h_cb -> {
//                    val s =it.changepercentage?.substring(1, it.changepercentage.length)
                    if (sortCheck) {
                        list.sortBy {
                            it.changePercentage.toString()
                        }
                        marketAdapter.refreshData(list)
                    } else {
                        list.sortByDescending { it.changePercentage.toString() }
                        marketAdapter.refreshData(list)
                    }
                }
            }

        }

    fun loadAll() {
        marketBeanViewModel.getMarketList()

//        if(TextUtils.isEmpty(sortType)){
//            coinViewModel.getMarketList()
//        }else {
//            coinViewModel.getMarketList(sortType, sortCheck)
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onFollowEvent(e: MarketEvent) {
        if (nav_rb_1.isChecked) {
            coinViewModel.getMarketList()
        }
    }
}